<?php
	/**
	* Change logs
	* Sep 12, 2011 - trungdt - Add agregate to article module
	*                          Now we should select the right location_data for new item 
	*                          Remark: dont do it when update   
	*/
	if (!defined("EXPONENT")) exit("");
	global $user;
	if ((!isset($user)) || ($user->id ==0)) exit("");

	$article = null;
	if (isset($_POST['id'])) { // edit
		$article = $db->selectObject('article', 'id='.$_POST['id']);
		if ($article != null) {
			$loc = unserialize($article->location_data);
		} 
		$config = $db->selectObject('articlemodule',"location_data='".serialize($loc)."'");
	} else {
		// Sep 12, 2011 - trungdt 
		// When we add new article 
		// Check & change the location-data
		// based on categories
		$temp=0;
		if (isset($_POST['categories']))
		{
			$temp=intval($_POST['categories']);
		}
		if ($temp > 0){ // test if valid category item
			$cat=$db->selectObject("category"," id = {$temp}");
			if ($cat){
				$loc=unserialize($cat->location_data); // OK, we select the right location_data
			}
		}
		
		$article->rank = $db->max('article', 'rank', 'location_data', "location_data='".serialize($loc)."'");
		if ($article->rank == null) {
			$article->rank = 0;
		} else { 
			$article->rank += 1;
		}
		$article->category_id=0;
	}

	if (exponent_permissions_check("manage",$loc)
	|| exponent_permissions_check("create",$loc)) {

		$oldcatid = $article->category_id;
		$article = article::update($_POST, $article);
		$article->ower_id = $user->id;
		$article->location_data = serialize($loc);
		/*if (isset($_POST['categories'])) {
		$article->category_id = $_POST['categories'];
		}*/
		if (isset($article->id)) {
			$article->id = $db->updateObject($article,"article");
		} else {
			$article->id = $db->insertObject($article,"article");
		}

		articlemodule::spiderContent($article);

		if ($oldcatid != $article->category_id) {
			$db->decrement('article', 'rank', 1, "location_data='".serialize($loc)."' AND rank > ".$article->rank." AND category_id=".$article->category_id);
		}

		exponent_flow_redirect();
	} else {
		echo SITE_403_HTML;
	}


?>